package com.zhia.demo.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zhia.demo.dao.ReviewDao;
import com.zhia.demo.entity.RecoverEntity;
import com.zhia.demo.entity.ReviewEntity;
import com.zhia.demo.service.RecoverService;
import com.zhia.demo.service.ReviewService;
import com.zhia.demo.service.UserLikeService;
import com.zhia.demo.service.UserService;
import com.zhia.demo.utils.Utils;
import com.zhia.demo.vo.RecoverVo;
import com.zhia.demo.vo.ReviewVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;


/**
 * @author DONG
 * @create 2023/11/4 15:38
 */
@Service
public class ReviewServiceImpl extends ServiceImpl<ReviewDao, ReviewEntity> implements ReviewService {
    @Autowired
    private UserService userService;

    @Autowired
    private RecoverService recoverService;

    @Autowired
    private UserLikeService userLikeService;

    @Override
    public List<ReviewVo> getReviewList(String bookId, Integer userId) {
        List<ReviewEntity> reviews = this.baseMapper.selectList(new QueryWrapper<ReviewEntity>().eq("book_id", bookId).orderByDesc("create_time"));
        return reviews.stream().map(item -> {
            ReviewVo reviewVo = new ReviewVo();
            BeanUtils.copyProperties(item, reviewVo);
            reviewVo.setReviewTime(Utils.formattingTime(item.getCreateTime()));
            reviewVo.setNickname(userService.getById(item.getUserId()).getNickname());
            List<RecoverVo> recoverVos = recoverService.getRecoverList(item.getId(),userId);
            if (recoverVos.size() > 0) {
                reviewVo.setRecovers(recoverVos);
            }
            if (userId != null) {
                reviewVo.setUserIsLike(userLikeService.getUserIsLikeReview(userId, "p" + item.getId()));
            }
            return reviewVo;
        }).collect(Collectors.toList());
    }

    @Override
    public void delete(Integer id) {
        recoverService.deleteByReviewId(id);
        this.baseMapper.deleteById(id);
    }

    @Override
    public void likeAdd(Integer id) {
        this.baseMapper.likeAdd(id);
    }

    @Override
    public void likeDec(Integer id) {
        this.baseMapper.likeDec(id);
    }
}
